package cn.zysheep.user.web;


import cn.zysheep.user.pojo.PatternProperties;
import cn.zysheep.user.pojo.User;
import cn.zysheep.user.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping("/user")
/**
 * 配置热更新
 * 方式一: 在@Value注入的变量所在类上添加注解@RefreshScope
 * 方式二: 使用@ConfigurationProperties注解代替@Value注解。
 */
//@RefreshScope
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private UserService userService;

//    @Value("${pattern.dateformat}")
//    private String dateformat;
    @Autowired
    private PatternProperties patternProperties;

    /**
     * 测试云配置热更新
     * @return
     */
    @GetMapping("now")
    public String now() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
    }

    /**
     * 测试多环境共享配置
     * 1、[spring.application.name]-[spring.profiles.active].yaml,例如: user-service-dev.yaml
     * 2、[spring.application.name].yaml,例如: user-service.yaml
     * 3、 而[spring.application.name].yaml不包含环境，因此可以被多个环境共享。
     * @return
     */
    @GetMapping("prop")
    public PatternProperties prop() {
        return patternProperties;
    }




    /**
     * 路径： /user/110
     *
     * @param id 用户id
     * @return 用户
     */
    @ApiOperation("查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", dataType = "String", paramType = "header", required = true)})
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userService.queryById(id);
    }


    @GetMapping("/payOrder")
    @HystrixCommand(fallbackMethod = "payOrderCallBack")
    public String payOrder() {
        String forObject = restTemplate.getForObject("http://pay-service/pay/payOrder", String.class);
        return forObject;
    }


    public String payOrderCallBack() {
        return "支付失败,执行熔断器方法";
    }

    @ApiOperation("保存用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", dataType = "String", paramType = "header", required = true)})
    @GetMapping("/saveUser")
    public ResponseEntity<?> saveUser() {
        return ResponseEntity.ok("保存成功");
    }
}
